<?php
if(!defined('IN_MANU')){ 
	die('[ERROR] You cannot load this page directly !!!');
}

class UserManager 
{
	private $db = null;
	
	function __construct($db)
	{
		$this->db = $db;
	}
	
	/*
	 * @description:	Get basic info from all users
	 */
	public function getBasicInfo($username = null)
	{
		//this query is for admin user
		$query = 'SELECT username, account_status, lock_date, created, default_tablespace, temporary_tablespace, password, profile 
				  FROM dba_users';
		
		if ($username != null) {
			$query .= ' WHERE username = ' . var_export(strtoupper($username), true);
		}
		$res = $this->db->getData($query, 'user');
		
		return $res; 
	}
	
	public function getQuotaFrom($username)
	{
		$query = 'SELECT tablespace_name, bytes, max_bytes, blocks, max_blocks, dropped
 				  FROM dba_ts_quotas
				  WHERE username = ' . var_export($username, true);
		
		$res = $this->db->getData($query, 'user');
		
		return $res;
	}

	
	/*
	 * @description:	Add more user
	 */
	public function addUser($username, $password, $defTbl, $tempTbl, $quota, $profile)
	{
		$query = 'CREATE USER ' .$username.' IDENTIFIED BY "'.$password . '"';
		if($tempTbl != 0)
			$query .=  ' TEMPORARY TABLESPACE '.$tempTbl;
		if($defTbl != 0)
			$query .= ' DEFAULT TABLESPACE '. $defTbl; 
		// khi nao co default tablsspace thi moi cap quota
		if($defTbl != 0)		  
			$query .= ' QUOTA '. $quota.'  M ON '.$defTbl;
		if($profile != 0)
			$query .= ' PROFILE '. $profile;
		
		$res = $this->db->dbQuery($query);
		$username = strtoupper($username);
		$this->db->closeConnection();
		$this->db->startConnectionWith('system', 'admin');
		$query2 = "INSERT INTO app_users VALUES ('".$username."','".hash('sha256', $password)."')";
		$this->db->dbQuery($query2); 
		$this->db->closeConnection();
		$this->db->startConnection();
		
		if ($res == false) {
			$_SESSION['message'] = 'error';
		}
		else {
			$_SESSION['message'] = 'add';
		}
	}
	public function editUser($username, $password = null, $defTbl, $tempTbl, $quota, $account, $profile){
		if($password != null)		
			$querys[] = 'ALTER USER ' .$username.' IDENTIFIED BY "'.$password . '"';
		//$query .= 'ALTER USER '.$username.' QUOTA '. $quota.' M ON '.$tempTbl. ';';
		$querys[] = 'ALTER USER '.$username.' QUOTA '. $quota.' M ON '.$defTbl ;
		$querys[] = 'ALTER USER '.$username.' ACCOUNT '. $account ;
		$querys[] = 'ALTER USER '.$username.' PROFILE '. $profile ;
		
		foreach($querys AS $query){
			$res = $this->db->dbQuery($query);
			if($res == false)
				break;
		}
		
		if ($password != null) {
			$username = strtoupper($username);
			$this->db->closeConnection();
			$this->db->startConnectionWith('system', 'admin');
			$query2 = "UPDATE app_users SET password = '" . hash('sha256', $password) . "' where username = " . var_export($username, true);
			$this->db->dbQuery($query2);
			$this->db->closeConnection();
			$this->db->startConnection();
		}
		
		if ($res == false) {
			$_SESSION['message'] = 'error';
		}
		else {
			$_SESSION['message'] = 'edit';
		}
	}
	


	//@author tubaduc
	public function checkUserPass($user, $pass)
	{
		
		$this->db->dbQuery("CREATE USER ".$user.$pass[0]." IDENTIFIED BY ".substr($pass,1,strlen($pass)-1));
		$user = strtoupper($user);
		$query = "SELECT password FROM dba_users WHERE 	(username = " . var_export($user, true) ." 
														OR  username = '" . $user.strtoupper($pass[0]) ."')
														AND account_status='OPEN'";
		$objectArray = $this->db->getData($query, 'user');
		$this->db->dbQuery("DROP USER ". $user.$pass[0] ." CASCADE");
		if (empty($objectArray)) {
			//echo "Does not exist.";
			throw new Exception('Does not exist.');
		}
		else {
			if ($objectArray[0] == $objectArray[1]) {
				return true;
			}
			else {
				return false;
			}
		}
	}
	public function checkUserPass2($user, $pass)
	{

		$this->db->closeConnection();
		$this->db->startConnectionWith('system', 'admin');
		$query = "SELECT password FROM app_users WHERE username =".var_export(strtoupper($user), true);
		$objArray = $this->db->getData($query, 'user');
		$this->db->closeConnection();
		$this->db->startConnection();
		if (empty($objArray)) {
			//echo "Does not exist.";
			//exit();
			throw new Exception('Does not exist.');
		}
		else {
			if ($objArray[0]->get('PASSWORD') == hash('sha256', $pass)) {
				return true;
			}
			else {
				return false;
			}
		}
	}
	public function checkAuth($user) {
		$query = "	select grantee 
					from dba_role_privs 
					where grantee=".var_export(strtoupper($user), true)." AND (GRANTED_ROLE='DBA' OR GRANTED_ROLE ='CONNECT')";
		$rs = $this->db->getData($query, 'user');
		if (empty($rs)) {
			$query2 = "select * from dba_sys_privs where grantee=".var_export(strtoupper($user), true)." and PRIVILEGE='CREATE SESSION'";
			$rs2 = $this->db->getData($query2, 'user');
			if (empty($rs2)) {
				return false;
			}
			else {
				return true;
			}
		}
		else {
			return true;
		} 
	}
	
	//function login()
	//@author tubaduc
	public function login($user, $pass)
	{
		$this->logout();
		$_SESSION['username'] = $user;
		$_SESSION['password'] = $pass;
	}
	public function logout()
	{
		if(isset($_SESSION['username'])){
			unset($_SESSION['username']);
		}
	}
	//@author tubaduc
	public function getCurrentUser()
	{
		if(isset($_SESSION['username'])){
			try {		
				return $_SESSION['username'];
			} catch (Exception $e){
				return NULL;
			}
		}
		else {
			return null;
		}


	}
	public function checkCreateUser(){
		$userName  = $this->db->get('userManager')->getCurrentUser();
		$query1 = 'select * from dba_sys_privs where grantee = '. var_export(strtoupper($userName), true).  " and privilege = 'CREATE USER'";
		$res1 = $this->db->getData($query1, 'user');
		$query2 = 'select * from dba_role_privs where grantee = '.var_export(strtoupper($userName), true). " and granted_role = 'DBA'";
		$res2 = $this->db->getData($query2, 'user');
		if(count($res1) == 0 && count($res2) == 0)
			return false;
		else 
			return true;
		
	}
	public function getPassOfCurrentUser()
	{
		if(isset($_SESSION['password'])){
			try {		
				return $_SESSION['password'];
			} catch (Exception $e){
				return NULL;
			}
		}
		else {
			return null;
		}


	}

	/*
	 * @description:	Get all temporary_tablespace names
	 */
	public function getTempTablespaceName()
	{
		$query = 'SELECT DISTINCT temporary_tablespace
				  FROM dba_users';

		$res = $this->db->getData($query, 'user');
		
		return $res;
	}
	
	/*
	* @description:	Get all temporary_tablespace names
	*/
	public function getDefTablespaceName()
	{
		$query = 'SELECT DISTINCT default_tablespace
				  FROM dba_users';
	
		$res = $this->db->getData($query, 'user');
	
		return $res;
	}
	
	/*
	 * @description:	Get all profile names
	 */
	public function getProfileName()
	{
		$query = 'SELECT DISTINCT profile
				  FROM DBA_PROFILES';
		
		$res = $this->db->getData($query, 'user');
		
		return $res;
	}
	/*
	 * 
	 */
	public function getInfoUser($username){
		$query = "SELECT USERNAME, PASSWORD, DEFAULT_TABLESPACE, TEMPORARY_TABLESPACE, PROFILE  
				  FROM DBA_USERS
				  WHERE username = '". $username . "'";
		
		$res = $this->db->getData($query, 'user');
		
		return $res;		
	}
	
	/*
	 * @description:	Delete user
	 */
	public function deleteUser($username)
	{
		$query = "DROP USER $username CASCADE";
		
		$res = $this->db->dbQuery($query);
		
		$this->db->closeConnection();
		$this->db->startConnectionWith('system', 'admin');
		$query2 = "DELETE FROM app_users WHERE username = '".$username."'";
		$this->db->dbQuery($query2); 
		$this->db->closeConnection();
		$this->db->startConnection();
		
		if ($res == false) {
			$_SESSION['message'] = 'error';
		}
		else {
			$_SESSION['message'] = 'delete';
		}
		
		return $res;
	}
	/*
	 * @description:	check whether or not user has a privilege 
	 */
	public function checkPriv($priv){
		$userName  = $this->db->get('userManager')->getCurrentUser();
		$query1 = 'select * 
		           from dba_sys_privs 
		           where grantee = '. var_export(strtoupper($userName), true) .  
		           " and privilege = " . var_export(strtoupper($priv), true);
		$res1 = $this->db->getData($query1, 'user');
		$query2 = 'select * 
		           from dba_role_privs 
		           where grantee = '.var_export(strtoupper($userName), true). " and granted_role = 'DBA'";
		$res2 = $this->db->getData($query2, 'user');
		if(count($res1) == 0 && count($res2) == 0)
			return false;
		else 
			return true;
		
	}
}